<?php
/*
 *      osadminka.php
 *      
 *      Copyright 2011 ViRak <vetalrakitin@gmail.com>
 *      
 *      This program is free software; you can redistribute it and/or modify
 *      it under the terms of the GNU General Public License as published by
 *      the Free Software Foundation; either version 2 of the License, or
 *      (at your option) any later version.
 *      
 *      This program is distributed in the hope that it will be useful,
 *      but WITHOUT ANY WARRANTY; without even the implied warranty of
 *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *      GNU General Public License for more details.
 *      
 *      You should have received a copy of the GNU General Public License
 *      along with this program; if not, write to the Free Software
 *      Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 *      MA 02110-1301, USA.
 */
require_once($_SERVER['DOCUMENT_ROOT']."/classes/interface/oscomponent.php");
//require_once($_SERVER['DOCUMENT_ROOT']."/classes/interface/osdbcombobox.php");
require_once($_SERVER['DOCUMENT_ROOT']."/classes/interface/osbutton.php");
require_once($_SERVER['DOCUMENT_ROOT']."/classes/interface/ostoolbar.php");
require_once($_SERVER['DOCUMENT_ROOT']."/classes/interface/oswindow.php");
require_once($_SERVER['DOCUMENT_ROOT']."/classes/interface/osedit.php");
require_once($_SERVER['DOCUMENT_ROOT']."/classes/interface/oscombobox.php");
require_once($_SERVER['DOCUMENT_ROOT']."/classes/interface/osmetadictionaryedit.php");
require_once($_SERVER['DOCUMENT_ROOT']."/classes/interface/osdictionariesedit.php");
require_once($_SERVER['DOCUMENT_ROOT']."/classes/DB/osmysqldb.php");
require_once($_SERVER['DOCUMENT_ROOT']."/classes/interface/oswddataedit.php");

class osadminka extends oscomponent {
	
	private $btmakechanges;
	private $btsavetofile;
	private $btopenfromfile;
	private $listbox1;
	private $frame1;
	private $mdframe;
	private $table_DB;
	private $table_MD;
	private $tables_to_add;
	private $tables_to_drop;
	private $tables_to_edit;
	private $fields_to_add;
	private $fields_to_drop;
	private $fields_to_edit;
	private $cbobjects;
	private $dictionariesedit;
	private $wdtest;
	private $tbsystem;
	//private $metadataDB;
	//private $metadata;
	//private $mdadd;

	function __construct($parent) {
		parent::__construct($parent);
		
		$this->btsavetofile = new osbutton(0);
		$this->btsavetofile->setevent($this, "onclick", "btsavetofileonclick");
		$this->btsavetofile->caption = "Сохранить";
		
		$this->btopenfromfile = new osbutton(0);
		$this->btopenfromfile->setevent($this, "onclick", "btopenfromfileonclick");
		$this->btopenfromfile->caption = "Открыть";
		
		$this->btmakechanges = new osbutton(0);
		$this->btmakechanges->setevent($this, "onclick", "btmakechangesonclick");
		$this->btmakechanges->caption = "Внести изменения в базу данных";

		$this->listbox1 = new oscombobox(0);
		
		//$this->listbox1->additem("Документы","Документы");
		//$this->listbox1->additem("Регистры","Регистры");
		$this->listbox1->setevent($this, "onchange", "listbox1onchange");
		
		$this->wdtest = new oswindow(0);
		$this->wdtest->caption = "Данные";
		
		$this->cbobjects = new oscombobox($this->wdtest->uuid);
		$this->cbobjects->additem("dictionaries","Справочники");
		$this->cbobjects->setevent($this, "onchange", "cbobjectsonchange");
		
		$this->mdframe = new osmetadictionaryedit(0);
		$this->dictionariesedit = new osdictionariesedit($this->wdtest->uuid);
		
		switch ($this->cbobjects->selecteditem()) {
			case "dictionaries":{$this->dictionariesedit->dictionaries = $_SESSION["metadata"]->dictionaries;break;}
		}
		
		$this->tbsystem = new ostoolbar(0);
		$this->tbsystem->additem("data", "Данные");
		$this->tbsystem->setevent($this, "onitemclick", "tbsystemonitemclick");

		$this->initialize();
	}
	
	function cbobjectsonchange($value) {
		$this->update();
	}
	
	function tbsystemonitemclick($itemname) {
		switch ($itemname) {
			case "data":{
				//$this->tbsystem->additem("metadata", "Метаданные");
				//$this->update();
				new oswddataedit(0);
				break;
			}
		}
	}

	private function initialize() {
		$metadata = $_SESSION["metadata"];
		$this->listbox1->deleteallitems();
		//$this->listbox1->additem("Справочники","Справочники (".$metadata->dictionaries->count().")");
		$this->listbox1->additem("dictionaries","Справочники");
		//$this->mdframe->dictionaries = $metadata->dictionaries;
		//$this->frame1 = $this->mdframe;
		//$this->listbox1onchange($this->listbox1->selecteditem());
		$this->mdframe->dictionaries = $_SESSION["metadata"]->dictionaries;
		$this->frame1 = $this->mdframe;
	}

	function btmakechangesonclick() {
		// Здесь должна быть жесть
		// Получаем информацию о текущем состоянии базы данных
		$sql = "select table_name from information_schema.tables where table_schema = 'test';";
		$my = new osmysqldb();
		if ($my->connect()) {
			$result = $my->select($sql);
		}
		$this->table_DB = array();
		foreach ($result as $item) {
			$this->table_DB[] = $item["table_name"];
		}
		// Получаем информацию о текущем состоянии метаданных
		$this->table_MD = array();
		foreach ($_SESSION["metadata"]->dictionaries->getall() as $dic) {
			$this->table_MD[] = $dic->uuid;
		}
		if (($this->table_DB) and ($this->table_MD)) {
			
			$this->tables_to_add = array_diff($this->table_MD, $this->table_DB);
			foreach ($this->tables_to_add as $dictionary_uuid) {
				$my->table_add($dictionary_uuid);
				foreach ($_SESSION["metadata"]->dictionaries->byuuid($dictionary_uuid)->fields->getall() as $field) {
					$type = $field->datatype;
					$length = $field->length;
					$my->field_add($dictionary_uuid, $field->uuid, $type."(".$length.")"); 
				}
			}
			
			$this->tables_to_drop = array_diff($this->table_DB, $this->table_MD);
			foreach ($this->tables_to_drop as $dictionary_uuid) {
				$my->table_drop($dictionary_uuid);
			}
			
			$this->tables_to_edit = array_diff($this->table_DB, $this->tables_to_add, $this->tables_to_drop);
			foreach ($this->tables_to_edit as $dictionary_uuid) {
				$sql = "select column_name from information_schema.columns where (table_schema = 'test') and (table_name = '".$dictionary_uuid."') and (column_name <> 'id') and (column_name <> 'owner');";
				$result = $my->select($sql);
				$fields_DB = array();
				foreach ($result as $item) {
					$fields_DB[] = $item["column_name"];
				}
				$fields_MD = array();
				foreach ($_SESSION["metadata"]->dictionaries->byuuid($dictionary_uuid)->fields->getall() as $field) {
					$fields_MD[] = $field->uuid;
				}
				
				$this->fields_to_add[$dictionary_uuid] = array_diff($fields_MD, $fields_DB);
				foreach ($this->fields_to_add[$dictionary_uuid] as $field_uuid) {
					$type = $_SESSION["metadata"]->dictionaries->byuuid($dictionary_uuid)->fields->byuuid($field_uuid)->type;
					$length = $_SESSION["metadata"]->dictionaries->byuuid($dictionary_uuid)->fields->byuuid($field_uuid)->length;
					$my->field_add($dictionary_uuid, $field_uuid, $type."(".$length.")"); 
				}
				
				$this->fields_to_drop[$dictionary_uuid] = array_diff($fields_DB, $fields_MD);
				foreach ($this->fields_to_drop[$dictionary_uuid] as $field_uuid) {
					$my->field_drop($dictionary_uuid, $field_uuid);
				}
				
				$this->fields_to_edit[$dictionary_uuid] = array_diff($fields_DB, $this->fields_to_add[$dictionary_uuid], $this->fields_to_drop[$dictionary_uuid]);
				foreach ($this->fields_to_edit[$dictionary_uuid] as $field_uuid) {
					$type = $_SESSION["metadata"]->dictionaries->byuuid($dictionary_uuid)->fields->byuuid($field_uuid)->datatype;
					$length = $_SESSION["metadata"]->dictionaries->byuuid($dictionary_uuid)->fields->byuuid($field_uuid)->length;
					$my->field_edit($dictionary_uuid, $field_uuid, $type."(".$length.")");
				}
			}	
		}
		//$this->update();
	}
	
	function btopenfromfileonclick() {
		$_SESSION["metadata"]->openfromfile("/home/vetal/openshift/meta.conf");
		//$this->initialize();
		$this->update();
	}
	
	function btsavetofileonclick() {
		$_SESSION["metadata"]->savetofile("/home/vetal/openshift/meta.conf");
	}
	
	function listbox1onchange($value) {
		switch ($value) {
			case "dictionaries":{
				$this->mdframe->dictionaries = $_SESSION["metadata"]->dictionaries;
				$this->frame1 = $this->mdframe;
				$this->update();
				break;
			}
			default:{
				$this->frame1 = null;
				$this->update();
				break;
			}
		}
	}
	
	function get() {
		$ret = $this->tbsystem->get();
		$ret .= "<div id=".$this->uuid;
		$ret .= ">";
		$ret .= "Админка<br>";
		$ret .= "<fieldset><legend>Метаданные</legend>";
		$ret .= $this->btopenfromfile->get().$this->btsavetofile->get().$this->btmakechanges->get()."<br>";
		$ret .= $this->listbox1->get()."<br>";
		if ($this->frame1) {
			$ret .= $this->frame1->get();
		}
		$ret .= "</fieldset>";
		$ret .= "<fieldset><legend>Данные</legend>";
		//$ret .= $this->cbobjects->get()."<br>";
		$ret .= $this->wdtest->get()."<br>";
/*
		switch ($this->cbobjects->selecteditem()) {
			case "dictionaries":{$this->dictionariesedit->dictionaries = $_SESSION["metadata"]->dictionaries;$ret .= $this->dictionariesedit->get();break;}
		}
*/
		$ret .= "</fieldset>";
		$ret .= "</div>";
		return $ret;
	}
}
?>
